<template>
  <div>
    <!-- 头部 -->
    <template>
      <header-option>
        <template v-slot:btn>
          <div>
            <cs-btn type="primary" btnText="添加" @click.native="alterInfodialogVisible(0, '')" />
            <cs-btn btnText="删除" @click.native="dellistfn" />
            <cs-btn btnText="导出" @click.native="exportfn" />
          </div>
        </template>
        <template v-slot:input>
          <el-input
            class="cs-input"
            placeholder="请输入关键字搜索"
            v-model.trim="listModel.keyword"
            clearable
          ></el-input>
          <cs-btn type="search" @click.native="searchBtnClick" btnText="查询" class="searcg_btn" />
        </template>
      </header-option>
    </template>
    <!-- 表格 -->
    <template>
      <cs-card>
        <el-table
          v-loading="isLoading"
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
          @selection-change="selectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="userName" label="登录名称" width="200"> </el-table-column>
          <el-table-column prop="nickName" label="用户名称" width="200"> </el-table-column>
          <!-- <el-table-column prop="siteName" label="所属站点" width="220"> </el-table-column> -->
          <el-table-column prop="phone" label="手机号" width="200">
            <template v-slot="scoped">
              {{ scoped.row.phone ? scoped.row.phone : '—' }}
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="200">
            <template v-slot="scoped">
              {{ scoped.row.email ? scoped.row.email : '—' }}
            </template>
          </el-table-column>
          <el-table-column label="用户状态" width="80">
            <template slot-scope="scope">
              <cs-text type="primary" v-if="scope.row.status == 1">可用</cs-text>
              <cs-text type="danger" v-else>停用</cs-text>
              <!-- <el-switch :value="scope.row.status  === 1 ? true : false" active-color="#006EFF" inactive-color="#B4B4B4">
              </el-switch> -->
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间"></el-table-column>
          <el-table-column fixed="right" label="操作" width="180">
            <template slot-scope="scope">
              <el-link
                type="primary"
                @click.native="alterInfodialogVisible(scope.row.id, scope.row)"
                >编辑</el-link
              >
              <el-link type="primary" @click="changePasswordFn(scope.row)">修改密码</el-link>
              <!-- <el-link type="primary" >分配角色</el-link> -->
            </template>
          </el-table-column>
        </el-table>
        <div id="pagination_section">
          <span class="currentSelect">{{ `已选${currentSelect}项，共${totalCount}项` }}</span>
          <div class="pagination_right">
            <span>{{ `${pageSize}条/页` }}</span>
            <cs-pagination
              :currentPage="currentPage"
              :totalPage="totalPage"
              @firstPageClick="firstPageClick"
              @previousPageClick="previousPageClick"
              @nextPageClick="nextPageClick"
              @lastPageClick="lastPageClick"
              @junkToOtherPage="junkToOtherPage"
            />
          </div>
        </div>
      </cs-card>
    </template>
    <!-- 修改框 -->
    <template>
      <el-dialog
        :title="title + '用户信息'"
        :visible.sync="dialogVisible"
        width="808px"
        class="dialogTitle"
        @closed="cancelBtnClick('alterForm')"
      >
        <el-form
          label-width="120px"
          ref="alterForm"
          :model="dialogData"
          :rules="rules"
          :key="'alterForm' + 1"
        >
          <el-form-item label="用户名称" class="el-form-item-text" prop="nickName" key="nickName">
            <el-input v-model.trim="dialogData.nickName"></el-input>
          </el-form-item>
          <!-- <el-form-item label="所属站点" prop="siteId" key="siteId">
            <el-select v-model="dialogData.siteId" class="form-select" clearable>
              <el-option
                v-for="(item, index) in sitelist"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="手机号码" prop="phone" key="phone">
            <el-input v-model.trim="dialogData.phone"></el-input>
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email" key="email">
            <el-input v-model.trim="dialogData.email"></el-input>
          </el-form-item>
          <el-form-item v-if="!isedit" label="登入名称" prop="userName" key="userName">
            <el-input v-model.trim="dialogData.userName"></el-input>
          </el-form-item>
          <el-form-item v-if="!isedit" label="登入密码" prop="password" key="password">
            <el-input v-model.trim="dialogData.password" show-password></el-input>
          </el-form-item>
          <el-form-item
            v-if="!isedit"
            label="确认密码"
            prop="confirmPassword"
            key="confirmPassword"
          >
            <el-input v-model.trim="dialogData.confirmPassword" show-password></el-input>
          </el-form-item>
          <el-form-item label="用户状态" prop="status" key="status">
            <el-switch v-model="dialogData.status" active-color="#006EFF" inactive-color="#B4B4B4">
            </el-switch>
          </el-form-item>
          <el-form-item label="用户性别" prop="sex" key="sex">
            <el-select v-model="dialogData.sex" class="form-select" clearable>
              <el-option label="男" :value="1"></el-option>
              <el-option label="女" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" class="spacingL" prop="remark" key="remark">
            <label slot="label">备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注</label>
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              resize="none"
              v-model.trim="dialogData.remark"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <cs-btn
            type="primary"
            @click.native="confirmBtnClick('alterForm')"
            btnText="确定"
            class="confirm_btn dialog_btn"
            :buttonStatus="buttonStatus"
          />
          <cs-btn @click.native="cancelBtnClick('alterForm')" btnText="取消" class="dialog_btn" />
        </div>
      </el-dialog>
    </template>
    <!-- 修改密码 -->
    <template>
      <el-dialog
        title="修改用户密码"
        :visible.sync="alterPasswordDialogVisible"
        width="808px"
        class="dialogTitle"
        @closed="cancelPasswordDataClick('alterPwdForm')"
      >
        <el-form
          label-width="120px"
          ref="alterPwdForm"
          :model="PasswordData"
          :rules="alterPwdRules"
        >
          <el-form-item label="登录名称">
            <el-input disabled v-model.trim="userName"></el-input>
          </el-form-item>
          <el-form-item label="原密码" prop="lastPassword">
            <el-input v-model.trim="PasswordData.lastPassword" show-password></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="password">
            <el-input v-model.trim="PasswordData.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model.trim="PasswordData.confirmPassword" show-password></el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <cs-btn
            type="primary"
            @click.native="confirmPasswordClick('alterPwdForm')"
            btnText="确认"
            class="confirm_btn dialog_btn"
            :buttonStatus="alterPwdBtnStatus"
          />
          <cs-btn
            @click.native="cancelPasswordDataClick('alterPwdForm')"
            btnText="取消"
            class="dialog_btn"
          />
        </div>
      </el-dialog>
    </template>
  </div>
</template>

<script>
import _ from 'lodash'

import headerOption from '@/components/headerOption/headerOption.vue'
import csBtn from '@/components/cs-btn/cs-btn.vue'
// import csLabel from '@/components/cs-label/cs-label.vue'
import csCard from '@/components/cs-card/cs-card.vue'
import csPagination from '@/components/cs-pagination/cs-pagination.vue'
import csText from '@/components/cs-text/cs-text.vue'
import {
  searchUser,
  getSiteNameAndId,
  addUser,
  updTenantUser,
  delUser,
  updPassword,
  userexport,
  isTheNameDuplicate,
  isrepeatEmail
} from '@/service/operate/user_manage/user_manage'
import { isPhoneCorrect, isEmailCorrect } from '@/utils/regularVerification'

export default {
  components: {
    headerOption,
    csBtn,
    csCard,
    csPagination,
    csText
  },
  data() {
    const checkename = async (rule, value, callback) => {
      const { data } = await isTheNameDuplicate({ userName: value })
      if (data.code === 0) {
        callback()
      } else {
        callback(new Error('用户名已存在'))
      }
    }
    const checkePassword = (rule, value, callback) => {
      if (value) {
        if (value !== this.dialogData.password) {
          callback(new Error('两次密码不一致'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const checkphone = (rule, value, callback) => {
      if (value) {
        if (!isPhoneCorrect(value)) {
          return callback(new Error('请输入正确的手机号码'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const checkemail = async (rule, value, callback) => {
      if (value) {
        if (!isEmailCorrect(value)) {
          return callback(new Error('请输入正确的邮箱'))
        } else {
          if (!this.isedit) {
            const { data } = await isrepeatEmail({ email: value })
            if (data.code === 0) {
              callback()
            } else {
              callback(new Error(data.msg))
            }
          } else {
            callback()
          }
        }
      } else {
        callback()
      }
    }
    const checkeAlterPassword = (rule, value, callback) => {
      if (value) {
        if (value !== this.PasswordData.password) {
          callback(new Error('两次密码不一致'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      isedit: false,
      buttonStatus: false,
      alterPwdBtnStatus: false,
      title: '',
      siteName: '',
      // 当前页码
      currentPage: 1,
      // 一页的条数
      pageSize: 10,
      // 总共多少条数据
      totalCount: 0,
      // 总共多少页
      totalPage: 0,
      currentSelect: 0,
      selectId: [],
      tableData: [],
      alterPasswordDialogVisible: false,
      userName: '',
      PasswordData: {
        id: '',
        password: '',
        confirmPassword: '',
        lastPassword: ''
      },
      dialogVisible: false,
      dialogData: {
        id: '',
        // siteId: '',
        userName: '',
        password: '',
        confirmPassword: '',
        nickName: '',
        phone: '',
        email: '',
        sex: null,
        remark: '',
        status: true
      },
      listModel: {
        offset: 1,
        limit: 10,
        keyword: ''
      },
      sitelist: [],
      rules: {
        nickName: [{ required: true, message: '请选择用户名', trigger: 'blur' }],
        // siteId: [{ required: true, message: '请选择站点', trigger: 'blur' }],
        phone: [
          // { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkphone, trigger: 'blur' }
        ],
        email: [
          // { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        confirmPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkePassword, trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: checkename, trigger: 'blur' }
        ],
        sex: [{ required: true, message: '请选择性别', trigger: 'blur' }]
      },
      alterPwdRules: {
        lastPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
        password: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
        confirmPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { validator: checkeAlterPassword, trigger: 'blur' }
        ]
      },
      isLoading: false
    }
  },
  watch: {
    'listModel.keyword'(newValue) {
      if (newValue === '') {
        this.getlist()
      }
    }
  },
  created() {
    this.getlist()
    this.getSitelist()
  },
  beforeDestroy() {
    this.$bus.$off('siteSelectNum')
  },
  methods: {
    // 搜索按钮点击事件
    searchBtnClick() {
      // 如果点击搜索时表格还在加载，则不允许发送请求
      if (this.isLoading) return
      this.getlist()
    },
    async exportfn() {
      const loading = this.$loading({
        lock: true,
        text: '下载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const { data } = await userexport(this.listModel)
      if (!!data) {
        const filename = '用户信息表.xlsx'
        const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
          window.navigator.msSaveBlob(blob, decodeURI(filename))
        } else {
          // 创建新的URL并指向File对象或者Blob对象的地址
          const blobURL = window.URL.createObjectURL(blob)
          // 创建a标签，用于跳转至下载链接
          const tempLink = document.createElement('a')
          tempLink.style.display = 'none'
          tempLink.href = blobURL
          tempLink.setAttribute('download', decodeURI(filename))
          // 兼容：某些浏览器不支持HTML5的download属性
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 挂载a标签
          document.body.appendChild(tempLink)
          tempLink.click()
          document.body.removeChild(tempLink)
          // 释放blob URL地址
          window.URL.revokeObjectURL(blobURL)
        }
        setTimeout(() => {
          loading.close()
        }, 2000)
      } else {
        setTimeout(() => {
          loading.close()
        }, 2000)
      }
    },
    getlist: _.throttle(async function () {
      this.isLoading = true
      const { data } = await searchUser(this.listModel)
      this.isLoading = false
      if (data.code === 0) {
        this.tableData = data.data.list
        this.currentPage = data.data.currPage
        this.pageSize = data.data.pageSize
        this.totalCount = data.data.totalCount
        this.totalPage = data.data.totalPage
      }
    }, 1000),
    async getSitelist() {
      this.isLoading = true
      const { data } = await getSiteNameAndId()
      this.isLoading = false
      if (data.code === 0) {
        this.sitelist = data.data
      }
    },
    alterInfodialogVisible(id, obj) {
      this.dialogVisible = true
      if (id === 0) {
        this.title = '添加'
        this.isedit = false
      } else {
        this.title = '编辑'
        this.isedit = true
        this.dialogData = {
          id: obj.id,
          // siteId: obj.siteId,
          nickName: obj.nickName,
          phone: obj.phone,
          email: obj.email,
          sex: obj.sex,
          remark: obj.remark,
          status: obj.status
        }
        if (obj.status === 1) {
          this.dialogData.status = true
        } else {
          this.dialogData.status = false
        }
      }
    },
    cancelBtnClick(alterForm) {
      this.$refs[alterForm].resetFields()
      this.dialogVisible = false
      this.dialogData = {
        id: '',
        // siteId: '',
        userName: '',
        password: '',
        nickName: '',
        phone: '',
        email: '',
        sex: null,
        remark: '',
        status: true
      }
    },
    changePasswordFn(obj) {
      console.log(obj)
      this.userName = obj.userName
      this.PasswordData.id = obj.id
      this.alterPasswordDialogVisible = true
    },
    async confirmPasswordClick(addForm) {
      this.alterPwdBtnStatus = true
      // if (this.PasswordData.password !== '' || this.PasswordData.lastPassword !== '') {
      this.$refs[addForm].validate(async (valid) => {
        if (valid) {
          const { data } = await updPassword(this.PasswordData)
          if (data.code === 0) {
            this.$message({
              message: data.msg,
              type: 'success'
            })
            this.alterPasswordDialogVisible = false
            await this.getlist()
          } else {
            this.$message.error(data.msg)
          }
          this.alterPwdBtnStatus = false
        } else {
          this.alterPwdBtnStatus = false
        }
      })

      // } else {
      //   this.$message.error('请完成密码填写')
      //   this.alterPwdBtnStatus = false
      //   return false
      // }
    },
    cancelPasswordDataClick(alterForm) {
      this.$refs[alterForm].resetFields()
      this.alterPasswordDialogVisible = false
      this.userName = ''
      this.PasswordData.id = ''
      this.PasswordData.lastPassword = ''
      this.PasswordData.password = ''
    },
    confirmBtnClick(addForm) {
      this.buttonStatus = true
      this.$refs[addForm].validate(async (valid) => {
        if (valid) {
          this.dialogData.status = this.dialogData.status ? 1 : 0
          try {
            if (this.dialogData.id === '') {
              const { data } = await addUser(this.dialogData)
              if (data.code === 0) {
                this.dialogVisible = false
                await this.getlist()
                this.$message({
                  message: `${this.title}用户信息成功`,
                  type: 'success'
                })
              } else {
                this.$message.error(data.msg)
              }
            } else {
              const { data } = await updTenantUser(this.dialogData)
              if (data.code === 0) {
                this.dialogVisible = false
                await this.getlist()
                this.$message({
                  message: `${this.title}用户信息成功`,
                  type: 'success'
                })
              } else {
                this.$message.error(data.msg)
              }
            }
          } catch (err) {
            console.log(err)
            this.$message.error('请求错误')
            setTimeout(() => {
              this.buttonStatus = false
            }, 500)
          }

          this.buttonStatus = false
        } else {
          // this.$message.error('请完成填写')
          this.buttonStatus = false
          return false
        }
      })
    },
    dellistfn() {
      if (this.selectId.length > 0) {
        const text = '您已选择' + this.currentSelect + '项，确认删除？'
        const _this = this
        this.$confirm(text)
          .then(async () => {
            const { data } = await delUser(this.selectId)
            if (data.code === 0) {
              _this.getlist()
              this.$message({
                message: '删除成功',
                type: 'success'
              })
            }
          })
          .catch((_) => {})
      } else {
        this.$message.error('没有已选选项，请选择后再操作!')
      }
    },
    // 表格选择项变化时触发事件
    selectionChange(selection) {
      this.selectId = []
      // 获取当前选择多少项
      this.currentSelect = selection.length
      this.$bus.$emit('siteSelectNum', this.currentSelect)
      selection.forEach((item) => {
        this.selectId.push(item.id)
      })
      console.log(this.selectId)
    },
    lastPageClick() {
      if (this.isLoading) return
      this.listModel.offset = this.totalPage
      this.getlist()
    },
    nextPageClick() {
      if (this.isLoading) return
      this.listModel.offset = this.currentPage + 1
      this.getlist()
    },
    previousPageClick() {
      this.listModel.offset = this.currentPage - 1
      this.getlist()
    },
    firstPageClick() {
      if (this.isLoading) return
      this.listModel.offset = 1
      this.getlist()
    },
    // 跳转页
    junkToOtherPage(page) {
      this.listModel.offset = page
      this.getlist()
    }
  }
}
</script>

<style scoped>
/* 头部样式start */
.cs-input {
  width: 276px !important;
}

.cs-input >>> .el-input__inner {
  width: 276px !important;
  height: 32px !important;
  border-radius: 0 !important;
}

.searcg_btn {
  margin-left: 16px;
  margin-right: 30px;
}

.el-input >>> .el-input__icon {
  line-height: 32px !important;
}
/* 头部样式end */
/* 更改el-select下拉框图标的行高 */
.el-select >>> .el-input__icon {
  line-height: 32px !important;
}

/* 更改el-select下拉框的图标 */
.el-select >>> .el-icon-arrow-up:before {
  content: '\e78f';
}

.el-form-item >>> .el-form-item__label {
  padding: 0;
  padding-right: 46px;
  color: #888888;
}
.el-select >>> .el-input__inner {
  border-radius: 0;
}

.el-input >>> .el-input__inner {
  border-radius: 0;
}

.el-textarea >>> .el-textarea__inner {
  border-radius: 0;
}

.form-select {
  width: 100%;
}

.dialogTitle >>> .el-dialog {
  padding: 6px 10px 18px 10px !important;
}

/* checkbox样式 */
.el-checkbox >>> .el-checkbox__inner {
  border-radius: 0;
}

.el-checkbox >>> .el-checkbox__inner::after {
  top: 0;
  left: 3px;
  border: 3px solid #fff;
  border-left: 0;
  border-top: 0;
  width: 4px;
}

.el-checkbox >>> .el-checkbox__label {
  color: #606266;
}

/* 去掉switch外层的div溢出隐藏 */
.el-table >>> .cell {
  overflow: visible;
}

/* 设置switch的宽高边框 */
.el-switch >>> .el-switch__core {
  width: 28px !important;
  height: 14px;
  border: 2px solid #dddddd !important;
}

/* 设置switch圆形按钮的宽高边框位置 */
.el-switch >>> .el-switch__core:after {
  top: -4px;
  width: 14px;
  height: 14px;
  border: 2px solid #dddddd;
}

/* 设置switch圆形按钮的激活位置 */
.el-switch.is-checked >>> .el-switch__core::after {
  left: 106%;
}

/* 设置switch圆形按钮的关闭位置 */
.el-switch >>> .el-switch__core:after {
  left: -2px;
}
/* 对话框样式end */
/* 表格样式start */
.el-form-item >>> .el-form-item__label {
  color: #888888;
}

.el-select >>> .el-input__inner {
  border-radius: 0;
}

.el-input >>> .el-input__inner {
  border-radius: 0;
}

.el-textarea >>> .el-textarea__inner {
  border-radius: 0;
}

.form-select {
  width: 100%;
}

.el-link {
  display: inline-block;
  margin-right: 16px;
}

/* 表格选择框样式start */
.el-table >>> .el-checkbox__inner {
  width: 20px;
  height: 20px;
}

.el-table >>> .el-checkbox__inner::after {
  top: 3px;
  left: 6px;
}

.el-table >>> .el-checkbox__inner::before {
  top: 8px;
}
/* 表格选择框样式end */

/* 去掉switch外层的div溢出隐藏 */
.el-table >>> .cell {
  overflow: visible;
}

/* 设置switch的宽高边框 */
.el-switch >>> .el-switch__core {
  width: 28px !important;
  height: 14px;
  border: 2px solid #dddddd !important;
}

/* 设置switch圆形按钮的宽高边框位置 */
.el-switch >>> .el-switch__core:after {
  top: -4px;
  width: 14px;
  height: 14px;
  border: 2px solid #dddddd;
}

/* 设置switch圆形按钮的激活位置 */
.el-switch.is-checked >>> .el-switch__core::after {
  left: 106%;
}

/* 设置switch圆形按钮的关闭位置 */
.el-switch >>> .el-switch__core:after {
  left: -2px;
}

/* 表格样式end */
</style>
